package com.rfzn.swipingcard

import android.app.ActivityManager
import android.content.Context
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import java.util.*
import kotlin.system.exitProcess

/**
 * Activity栈任务管理器
 * 通常放在我们自定义Activity的基类中操作
 */
class AcitivityManager private constructor() {

    private val activityStack: Stack<AppCompatActivity> = Stack()

    companion object {
        private const val TAG = "AcitivityManager"
        val instance: AcitivityManager by lazy { AcitivityManager() }

    }

    /**
     * 添加Activity
     */
    fun addActivity(activity: AppCompatActivity) {
        activityStack.add(activity)
        Log.e(TAG, "添加Activity后：${activityStack.toString()}")
    }

    /**
     * 移出存在的Activity
     */
    fun removeActivity(activity: AppCompatActivity) {
        if (activityStack.contains(activity)) {
            activity.finish()
            activityStack.remove(activity)
            Log.e(TAG, "移出存在的Activity后：${activityStack.toString()}")
        }


    }

    /**
     * 获取最上面的Activity
     */
    fun getTopActivity(): AppCompatActivity {
        return activityStack.lastElement()
    }

    /**
     * 清除Activity栈
     */
    fun clearActivity() {
        for (activity in activityStack) {
            activity.finish()
        }
        activityStack.clear()
    }

    /*
        退出应用程序
     */
    fun exitApp(context: Context) {
        //先清除Activity
        clearActivity()
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        //再killProcesses
        activityManager.killBackgroundProcesses(context.packageName)
        exitProcess(0)
    }
}